function base64Encode(str) {
  var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  var result = '';
  var i = 0;
  while (i < str.length) {
    var a = str.charCodeAt(i++);
    var b = i < str.length ? str.charCodeAt(i++) : 0;
    var c = i < str.length ? str.charCodeAt(i++) : 0;
    var bitmap = a << 16 | b << 8 | c;
    result += chars.charAt(bitmap >> 18 & 63) + chars.charAt(bitmap >> 12 & 63) + (i - 2 < str.length ? chars.charAt(bitmap >> 6 & 63) : '=') + (i - 1 < str.length ? chars.charAt(bitmap & 63) : '=');
  }
  return result;
}
function SMTPClient(config) {
  this.host = config.host || 'smtp.qq.com';
  this.port = config.port || 587;
  this.secure = config.secure || false;
  this.auth = config.auth || {};
  this.socket = null;
}
SMTPClient.prototype.sendCommand = function (command) {
  try {
    console.log("[email copy|L50]", 'SMTP Command:', command);
    return '250 OK';
  } catch (error) {
    throw new Error('SMTP命令发送失败: ' + error.message);
  }
};
SMTPClient.prototype.connect = function () {
  var self = this;
  return new Promise(function (resolve, reject) {
    try {
      console.log("[email copy|L66]", '连接到SMTP服务器:', self.host + ':' + self.port);
      self.sendCommand('EHLO localhost');
      if (self.auth.user && self.auth.pass) {
        self.sendCommand('AUTH LOGIN');
        self.sendCommand(base64Encode(self.auth.user));
        self.sendCommand(base64Encode(self.auth.pass));
      }
      resolve('连接成功');
    } catch (error) {
      reject(error);
    }
  });
};
SMTPClient.prototype.sendMail = function (mailOptions) {
  var self = this;
  return new Promise(function (resolve, reject) {
    try {
      self.sendCommand('MAIL FROM:<' + mailOptions.from + '>');
      self.sendCommand('RCPT TO:<' + mailOptions.to + '>');
      self.sendCommand('DATA');
      var emailContent = ['From: ' + mailOptions.from, 'To: ' + mailOptions.to, 'Subject: ' + mailOptions.subject, 'Content-Type: text/plain; charset=UTF-8', '', mailOptions.text || mailOptions.html || ''].join('\r\n');
      self.sendCommand(emailContent + '\r\n.');
      console.log("[email copy|L111]", '邮件发送成功');
      console.log("[email copy|L112]", '主题:', mailOptions.subject);
      console.log("[email copy|L113]", '内容:', mailOptions.text);
      resolve({
        messageId: 'autojs-' + Date.now(),
        response: '250 OK',
        envelope: {
          from: mailOptions.from,
          to: [mailOptions.to]
        }
      });
    } catch (error) {
      reject(error);
    }
  });
};
function sendEmailViaAPI(mailOptions) {
  return new Promise(function (resolve, reject) {
    try {
      var url = 'https://api.emailjs.com/api/v1.0/email/send';
      var data = {
        service_id: 'your_service_id',
        template_id: 'your_template_id',
        user_id: 'your_user_id',
        template_params: {
          to_email: mailOptions.to,
          subject: mailOptions.subject,
          message: mailOptions.text
        }
      };
      var response = http.postJson(url, data);
      if (response.statusCode === 200) {
        console.log("[email copy|L154|CsendEmailViaAPI()]", '邮件通过API发送成功');
        resolve({
          messageId: 'api-' + Date.now(),
          response: response.body.string()
        });
      } else {
        reject(new Error('API发送失败: ' + response.statusCode));
      }
    } catch (error) {
      reject(error);
    }
  });
}
function EmailJSConfig() {
  this.publicKey = 'zxRZ-2i94i2JolDs0';
  this.serviceId = 'service_qq';
  this.templateId = 'template_olbpznr';
  this.apiUrl = 'https://api.emailjs.com/api/v1.0/email/send';
}
function EmailJSClient(config) {
  this.config = config || new EmailJSConfig();
}
EmailJSClient.prototype.sendMail = function (mailOptions) {
  var self = this;
  return new Promise(function (resolve, reject) {
    try {
      var requestData = {
        service_id: self.config.serviceId,
        template_id: self.config.templateId,
        user_id: self.config.publicKey,
        template_params: {
          to_email: mailOptions.to,
          subject: mailOptions.subject,
          message: mailOptions.text,
          from_name: mailOptions.fromName || 'AutoJS应用'
        }
      };
      console.log("[email copy|L219]", '[EmailJS] 开始发送邮件...');
      console.log("[email copy|L220]", '[EmailJS] 收件人:', mailOptions.to);
      console.log("[email copy|L221]", '[EmailJS] 主题:', mailOptions.subject);
      var response = http.postJson(self.config.apiUrl, requestData, {
        headers: {
          'Content-Type': 'application/json',
          'User-Agent': 'AutoJS-EmailClient/1.0'
        },
        timeout: 10000
      });
      if (response.statusCode === 200) {
        console.log("[email copy|L234]", '[EmailJS] 邮件发送成功');
        var responseBody = response.body.string();
        resolve({
          success: true,
          messageId: 'emailjs-' + Date.now(),
          response: responseBody,
          service: 'EmailJS'
        });
      } else {
        console.error("[email copy|L243]", '[EmailJS] 发送失败，状态码:', response.statusCode);
        var errorBody = response.body.string();
        reject(new Error('EmailJS发送失败: ' + response.statusCode + ' - ' + errorBody));
      }
    } catch (error) {
      console.error("[email copy|L248]", '[EmailJS] 发送异常:', error.message);
      reject(error);
    }
  });
};
var defaultEmailClient = new EmailJSClient();
module.exports = {
  sendEmail: function (options) {
    return defaultEmailClient.sendMail({
      to: options.to || '1021969874@qq.com',
      subject: options.subject || '',
      text: options.text || '',
      fromName: options.fromName || 'AutoJS应用'
    });
  },
  createClient: function (config) {
    return new EmailJSClient(config);
  },
  createTransport: function (config) {
    var client = config ? new EmailJSClient(config) : defaultEmailClient;
    return {
      sendMail: function (mailOptions) {
        return client.sendMail({
          to: mailOptions.to,
          subject: mailOptions.subject,
          text: mailOptions.text,
          fromName: mailOptions.fromName
        });
      }
    };
  },
  updateConfig: function (config) {
    defaultEmailClient.config = Object.assign(defaultEmailClient.config, config);
    console.log("[email copy|L313|C -> updateConfig]", '[EmailJS] 配置已更新');
  }
};